package com.hmdp.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.text.Collator;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@RequiredArgsConstructor
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {
    private final StringRedisTemplate stringRedisTemplate;

    @Override
    public List<ShopType> queryList() {
        //1.在redis中查询数据
        String shopTypeJson = stringRedisTemplate.opsForValue().get("cache:shop:type");
        //2.如果存在，直接返回数据
        List<ShopType> shopTypeList = new ArrayList<>();
        if (StrUtil.isNotBlank(shopTypeJson)) {
             shopTypeList = JSONUtil.toList(shopTypeJson, ShopType.class);
            return shopTypeList;
        }
        //3.不存在，在数据库中查询数据
         shopTypeList = lambdaQuery().orderByAsc(ShopType::getSort).list();
        //4.不存在，跑错误
        if(CollUtil.isEmpty(shopTypeList)){
            return null;
        }
        //5.存在，返回结果，并将结果写入redis缓存中
        stringRedisTemplate.opsForValue().set("cache:shop:type", JSONUtil.toJsonStr(shopTypeList));
        return shopTypeList;
    }
}
